﻿var toolbar = null;
var editor = null;
var oneAndTwo = 0

$(document).ready(async function () {

    //父级类别下拉框绑定选择事件
    $("#ParentCategoryIds").combobox({
        onSelect: function (e) {       
            if (e != -1) {
                $.ajax({
                    url: '~/Brand/CategorysGetByParentID/' + e.value,
                    contentType: 'application/json',
                     success: async function (tps) {
                        if (tps != null) {
                            $('#ChildCategoryIds').empty()
                            $('#ChildCategoryIds').combobox({
                                valueField: 'Id',
                                textField: 'CategoryName',
                                data:tps
                            })
                            
                            if (oneAndTwo <2) {//如果第一次和第二次父类值改变 选择原来子类别
                                let initSelectedParentID = $("#initSelectedParentID").val()
                                let initSelectedCategoryID = $("#initSelectedCategoryID").val()
                                $("#ParentCategoryIds").combobox("setValue", initSelectedParentID)
                                if (initSelectedCategoryID!=-1)
                                $("#ChildCategoryIds").combobox("setValue", initSelectedCategoryID)

                                oneAndTwo++;
                            }
                            else {//否则 选择子类别的第一个
                                $("#ChildCategoryIds").combobox("setValue", tps[0].Id)
                            }
                        }

                    }
                })
            }
        }
    })


    /*#regrion富文本初始化*/
    var toolbar = [
        ['undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'pagebreak', 'horizontal', 'date', 'time', '|', 
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 
        ]
    ];

    var brand = null
    var id = parseInt($("#edit-brand-form").find("#Id").val());
    if (id > 0) {
        await $.ajax({
            url: "~/Brand/GetBrandByID/" + id,
            type: "POST",
            contentType: 'application/json',
            success: function (e) {
                if (e != null) {
                    brand = e
                }

            },
            error: function (e) {
                alert("error:" + e);
            }
        });
    }
    var ctls = ['BrandDetails', 'FranchiseAdvantages', 'FranchiseConditions', 'FranchiseProcess'];
    ctls.forEach(e => {
        var editor = UE.getEditor('editor-text-area-' + e, { zIndex: 9801, autoHeightEnabled: true, toolbars: toolbar, initialFrameWidth:950 });
        if (brand != null) {
            editor.ready(function () {
                UE.getEditor("editor-text-area-" + e).setContent(brand.BrandExtension[e]);
            })
        }
    })

    /*#endregion}*/

    /* 上传图片初始化*/
    $('#_upload_img_btn').fileupload({
        dropZone: null,
        url: $.Content("~/Brand/Controller?action=uploadimage"),
        autoUpload: false, maxFileSize: 999000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
        previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        var imgForm = $("#image-form");
        var imgList = $("#image-panel-list");
        var imgItem = $("<li class='image-item'><img class='img'/></li>");
        data.context = imgItem.appendTo(imgList);
        $.each(data.files, function (index, file) {
            var name = $("<div class='anme' title='" + file.name + "'>" + file.name + "</span>");
            var remove = $("<i class='fa fa-remove remove' title='删除'></i>");
            remove.click(function () { BrandImageDelete(this, $(this).attr("barndId"), $(this).attr("fileId")); });
            var p1 = $("<div style='display:inline-block'></div>");
            var item = $("<div class='img-name'>");
            remove.appendTo(p1); name.appendTo(p1); p1.appendTo(item);
            item.appendTo(data.context);
        });
        data.context.data("data", { jXHR: data.submit() });
    }).on('fileuploaddone', function (e, data) {
        var imgForm = $("#image-form");
        var d = data.result.Data;
        data.context.find(".img").attr("src", d.ImagePath);
        var rm = data.context.find(".remove");
        rm.attr("barndId", d.BrandID);
        rm.attr("fileId", d.Id);
        var ck = data.context.find("input[type='checkbox']");
        ck.attr("barndId", d.BrandID);
        ck.attr("fileId", d.Id);
    }).on('fileuploadsubmit', function (e, data) {
        var brandId = CheckBrandID();
        var userId = CheckEditorID();
        data.formData = { BrandID: brandId, UserID: userId };
    }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
});

//获取门店数量
function GetStoreCount(form) {
    var v = parseInt(form.find("#StoreCount").val());
    if (isNaN(v) || v == null) { v = 0; }
    return v;
}

//获取选择类别id
function GetChildCategoryId(form) {
    var v = parseInt(form.find("#ChildCategoryIds").combobox("getValue"));
    if (isNaN(v) || v == null) { v = 0; }
    return v;
}
//获取投资金额
function GetAmount(form) {
    var v = parseInt(form.find("#Amount").combobox("getValue"));
    if (isNaN(v) || v == null) { v = 0; }
    return v;
}

//获取区域id
function GetFranchiseRegionID(form) {
    var v = parseInt(form.find("#FranchiseRegionId").combobox("getValue"));
    if (isNaN(v) || v == null) { v = 0; }
    return v;
}


function CheckBrandID() {
    var form = $("#edit-brand-form");
    var id = parseInt(form.find("#Id").val());
    if (id <= 0) {
        if (SaveBrand(true)) {
            id = parseInt(form.find("#Id").val());
        }
    }
    return id;
}

function CheckEditorID() {
    var form = $("#edit-brand-form");
    var id = parseInt(form.find("#EditorID").val());
    return id;
}

//提交审核
function SubmitAudit() {
    var form = $("#edit-brand-form");
    var id = parseInt(form.find("#Id").val());
    if (SaveBrand(true)) {
        id = parseInt(form.find("#Id").val());
        $.ajax({
            url: "~/Brand/SubmitAudit/" + id,
            type: "POST",
            contentType: 'application/json',
            success: function (e) {
                if (e.Result) {
                    $.messager.alert('提交审核', '提交审核成功！', 'info', function () {
                        location.href = $.Content("~/Brand/BrandIndex");
                    });
                } else {
                    $.messager.alert('提交审核', '提交审核失败，请检查必要的信息是否填写!', 'error');
                }
            },
            error: function (e) {
                alert("error:" + e);
            }
        });
    }
}

//保存
function SaveBrand(sync) {
    var result = false;
    if (sync == undefined) { sync = false; }
    var form = $("#edit-brand-form");
    if (form.form('enableValidation').form('validate')) {
        var editor_BrandDetails = UE.getEditor('editor-text-area-' + 'BrandDetails');
        var editor_FranchiseAdvantages = UE.getEditor('editor-text-area-' + 'FranchiseAdvantages');
        var editor_FranchiseConditions = UE.getEditor('editor-text-area-' + 'FranchiseConditions');
        var editor_FranchiseProcess = UE.getEditor('editor-text-area-' + 'FranchiseProcess');
        var item = {
            Id: parseInt(form.find("#Id").val()),
            EditorID: parseInt(form.find("#EditorID").val()),
            FranchiseRegionID: GetFranchiseRegionID(form),
            CategoryID: GetChildCategoryId(form),
            Name: form.find("#Name").val(),
            Amount: GetAmount(form),
            StoreCount: GetStoreCount(form),
            MainProduct: form.find("#MainProduct").val(),
            TargetAudience: form.find("#TargetAudience").val(),
            DevelopmentModel: form.find("#DevelopmentModel").val(), 
            FranchiseWebsite: form.find("#FranchiseWebsite").val(),
            Brief: form.find("#Brief").val(),
            BrandExtension: {
                BrandDetails: editor_BrandDetails.getContent(),
                FranchiseAdvantages: editor_FranchiseAdvantages.getContent(),
                FranchiseConditions: editor_FranchiseConditions.getContent(),
                FranchiseProcess: editor_FranchiseProcess.getContent()
            },
        };

    
        $.ajax({
            async: !sync,
            url: "~/Brand/SaveBrand",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(item),
            success: function (e) {
                if (e.Result) {
                    
                    form.find("#Id").val(e.Data.Id);
                    form.find("#Name").val(e.Data.Name);
                    form.find("#EditorID").val(e.Data.EditorID)
                    result = true;
                    if (!sync) {
                        $.messager.show({
                            msg: '保存成功!',
                            showType: 'show'
                        });
                    }
                }
            },
            error: function (e) {
                alert("error:" + e);
            }
        });
    }
    return result;
}

function BrandImageDelete(p, brandId, fileId) {
    $.messager.confirm('删除', '确定要删除图片?', function (r) {
        if (r) {
            $.ajax({
                url: "~/Brand/BrandImageDelete?brandId=" + brandId + "&fileId=" + fileId,
                type: "DELETE",
                success: function (e) {
                    if (e.Result) {
                        $(p).parent().parent().parent().remove();
                    } else {
                        $.messager.alert('删除失败', '删除失败!', 'error');
                    }
                },
                error: function (e) {
                    alert("error:" + e);
                }
            });
        }
    });
}

